<template>
  <div class="authority">
    <!-- <warning-bar title="注：右上角头像下拉可切换角色" /> -->
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addAuthority()">新增角色</el-button>
      </div>
      <el-table :data="tableData" v-loading="loading"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                row-key="roleId" style="width: 100%">
        <el-table-column label="角色ID" min-width="160" prop="roleId"/>
        <el-table-column align="left" label="角色名称" min-width="160" prop="roleName"/>
        <el-table-column align="left" label="创建时间" min-width="160" prop="createTime"/>
        <el-table-column align="left" label="修改时间" min-width="160" prop="updateTime"/>
        <el-table-column align="left" label="操作" width="460">
          <template #default="scope">
            <el-button icon="setting" type="primary" link @click="opdendrawer(scope.row)">设置权限</el-button>
            <el-button icon="edit" type="primary" link @click="editAuthority(scope.row)">编辑</el-button>
            <el-button icon="delete" type="primary" link @click="deleteAuth(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="pageSize"
                       :page-sizes="[10, 30, 50, 100]" :total="total"
                       layout="total, sizes, prev, pager, next, jumper"
                       :hide-on-single-page="pageSize===10"
                       @current-change="handleCurrentChange" @size-change="handleSizeChange"/>
      </div>
    </div>
    <!-- 新增角色弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form ref="authorityForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="form.roleId" :disabled="dialogType === 'edit'" autocomplete="off" maxlength="15"/>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="form.roleName" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-if="drawer" v-model="drawer" custom-class="auth-drawer" :with-header="false" size="40%"
               title="角色配置">
      <el-tabs :before-leave="autoEnter" type="border-card">
        <el-tab-pane label="角色菜单">
          <Menus ref="menus" :row="activeRow" @changeRow="changeRow"/>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>


<script setup>
import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
} from '@/api/authority'


import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'


defineOptions({
  name: 'Authority'
})

const mustUint = (rule, value, callback) => {
  if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
    return callback(new Error('请输入正整数'))
  }
  return callback()
}


const drawer = ref(false)
const dialogType = ref('add')
const activeRow = ref({})

const dialogTitle = ref('新增角色')
const dialogFormVisible = ref(false)
const apiDialogFlag = ref(false)

const form = ref({
  roleId: '',
  roleName: ''
})
const rules = ref({
  roleId: [
    {required: true, message: '请输入角色ID', trigger: 'blur'},
    {validator: mustUint, trigger: 'blur', message: '必须为正整数'}
  ],
  roleName: [
    {required: true, message: '请输入角色名', trigger: 'blur'}
  ]
})
const loading = ref(true)
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 查询
const getTableData = async () => {
  loading.value = true
  const table = await getAuthorityList({page: page.value, pageSize: pageSize.value, ...searchInfo.value})
  if (table.code === 0) {
    tableData.value = table.data.records
    total.value = +table.data.total
    loading.value = false
  }
}


const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

getTableData()

const changeRow = (key, value) => {
  activeRow.value[key] = value
}
const menus = ref(null)
const apis = ref(null)
const datas = ref(null)
const autoEnter = (activeName, oldActiveName) => {
  const paneArr = [menus, apis, datas]
  if (oldActiveName) {
    if (paneArr[oldActiveName].value.needConfirm) {
      paneArr[oldActiveName].value.enterAndNext()
      paneArr[oldActiveName].value.needConfirm = false
    }
  }
}

const opdendrawer = (row) => {
  drawer.value = true
  activeRow.value = row
}

// 删除角色
const deleteAuth = (row) => {
  ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        const res = await deleteAuthority(row.roleId)
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          if (tableData.value.length === 1 && page.value > 1) {
            page.value--
          }
          getTableData()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        })
      })
}
// 初始化表单
const authorityForm = ref(null)
const initForm = () => {
  if (authorityForm.value) {
    authorityForm.value.resetFields()
  }
  form.value = {
    roleId: '',
    roleName: '',
  }
}
// 关闭窗口
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
  apiDialogFlag.value = false
}
// 确定弹窗

const enterDialog = () => {
  authorityForm.value.validate(async valid => {
    if (valid) {
      form.value.authorityId = Number(form.value.authorityId)
      switch (dialogType.value) {
        case 'add': {
          const res = await createAuthority(form.value)
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '添加成功!'
            })
            getTableData()
            closeDialog()
          }
        }
          break
        case 'edit': {
          const res = await updateAuthority(form.value)
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '添加成功!'
            })
            getTableData()
            closeDialog()
          }
        }
          break
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
// 增加角色
const addAuthority = () => {
  initForm()
  dialogTitle.value = '新增角色'
  dialogType.value = 'add'
  dialogFormVisible.value = true
}
// 编辑角色
const editAuthority = (row) => {
  dialogTitle.value = '编辑角色'
  dialogType.value = 'edit'
  for (const key in form.value) {
    form.value[key] = row[key]
  }
  dialogFormVisible.value = true
}

</script>

<style lang="scss">
.authority {
  .el-input-number {
    margin-left: 15px;

    span {
      display: none;
    }
  }
}

.tree-content {
  margin-top: 10px;
  height: calc(100vh - 158px);
  overflow: auto;
}
</style>
